package server.config;

import server.utils.ParseExpress;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.concurrent.*;

/**
 * @author cg
 * @date 2023/6/12 10:02
 */
public class ThreadPollConfig {
    private Properties properties;

    private int coreSize;

    private int maxSize;

    private long keepAliveTime;

    private int waitSize;

    private final String prefix = "threadpool.";
    private static volatile ThreadPoolExecutor poolExecutor;


    public static ThreadPoolExecutor getThreadPool(String path) {
        if (poolExecutor == null) {
            synchronized (ThreadPollConfig.class) {
                if (poolExecutor == null) {
                    new ThreadPollConfig(path);
                    return poolExecutor;
                }
            }
        }
        return poolExecutor;
    }

    private ThreadPollConfig() {
    }

    private ThreadPollConfig(String path) {
        this.properties = new Properties();
        try {
            this.properties.load(this.getClass().getClassLoader().getResourceAsStream(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String coreSize = properties.getProperty(prefix + "coreSize");
        this.coreSize = coreSize == null ? 10 : Integer.parseInt(coreSize);

        String maxsize = properties.getProperty(prefix + "maxSize");
        this.maxSize = maxsize == null ? 10 : Integer.parseInt(maxsize);

        String waitSize = properties.getProperty(prefix + "waitSize");

        this.waitSize = waitSize == null ? Integer.MAX_VALUE : Integer.parseInt(waitSize);

        String keepAliveTime = properties.getProperty(prefix + "keepAliveTime");
        this.keepAliveTime = keepAliveTime == null ? (1000 * 60) : ParseExpress.parseLong(keepAliveTime);
        properties.clear();
        poolExecutor = new ThreadPoolExecutor(this.coreSize, this.maxSize, this.keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(this.waitSize));
    }
}
